package com.example.painting;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

import androidx.annotation.Nullable;

import java.util.ArrayList;
import java.util.List;

public class CustomView extends View {

    List<Path> listStrokes = new ArrayList<>();
    Path pathStroke;
    Bitmap memBMP;
    Paint memPaint;
    Canvas memCanvas;
    boolean onTouch = false;

    float oldX;
    float oldY;

    public CustomView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    public boolean onTouchEvent(MotionEvent event){
        float x = event.getX();
        float y = event.getY();

        //设置触摸监听
        switch (event.getAction()){
            case MotionEvent.ACTION_DOWN:
                pathStroke = new Path();
                pathStroke.moveTo(x, y);
                oldX = x;
                oldY = y;
                onTouch = true;
                listStrokes.add(pathStroke);
                break;
            case MotionEvent.ACTION_MOVE:
                if(onTouch){
                    pathStroke.quadTo(oldX, oldY, x, y);
                    oldX = x;
                    oldY = y;
                    drawStrokes();
                }
                break;
            case MotionEvent.ACTION_UP:
                if(onTouch){
                    pathStroke.quadTo(oldX, oldY, x, y);
                    drawStrokes();
                    onTouch = false;
                }
                break;
        }
        return true;
    }

    public void drawStrokes(){
        if(memCanvas == null){
            memBMP = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888);
            memCanvas = new Canvas();//缓冲画布
            memCanvas.setBitmap(memBMP);//为画布设置位图Bitmap
            memPaint = new Paint();//设置画笔
            memPaint.setAntiAlias(true);//设置画笔抗锯齿
            memPaint.setColor(Color.RED);//设置画笔颜色
            memPaint.setStyle(Paint.Style.STROKE);//设置填充类型
            memPaint.setStrokeWidth(5);//画笔宽度
        }

        for(Path path : listStrokes){
            memCanvas.drawPath(path, memPaint);
        }

        invalidate();//刷新屏幕
    }

    @Override
    protected void onDraw(Canvas canvas){
        @SuppressLint("DrawAllocation")
        Paint paint = new Paint();
        if(memBMP != null)
            canvas.drawBitmap(memBMP, 0, 0, paint);

    }

}
